//
//  TBSharePOPView.swift
//  LeGou
//
//  Created by lxm on 2022/7/28.
//

import UIKit

class TBSharePOPView: XMBaseView, UICollectionViewDelegate, UICollectionViewDataSource {

    //MARK: --------------------属性--------------------
    var goodsInfo = ZMUtil.fastNilBehavior(type: TBGoodsDetail.self)
    var jdGoodsInfo = ZMUtil.fastNilBehavior(type: JDGoodsModel.self)
    var pddGoodsInfo = ZMUtil.fastNilBehavior(type: PDDModel.self)
    var linkInfo = ZMUtil.fastNilBehavior(type: TBLinkInfo.self)
    let disposeBag = DisposeBag()
    var imgArr = [[String:String]]()
    var selectImgcount = 0
    var saveSuccess = 0
    
    //MARK: --------------------UI控件--------------------
    @IBOutlet weak var contentView: UIView!
    // 保存图片
    @IBOutlet weak var imgCount: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    
    // 分享内容
    @IBOutlet weak var shareTxtView: UITextView!
    @IBOutlet weak var copyTxt: UIButton!
    
    // 下载地址
    @IBOutlet weak var addressBtn: UIButton!
    // 邀请码
    @IBOutlet weak var inviteBtn: UIButton!
    // 复制链接，文案
    @IBOutlet weak var copyLinkBtn: UIButton!
    @IBOutlet weak var copyTxtBtn: UIButton!
    // 分享
    @IBOutlet weak var shareWXBtn: UIButton!
    @IBOutlet weak var shareFrindBtn: UIButton!
    @IBOutlet weak var shareCopyBtn: UIButton!
    @IBOutlet weak var shareSaveBtn: UIButton!
    
    // 海报
    lazy var poster: TBSharePosterView = {
        let view = ZMUtil.loadNibView(nibName: TBSharePosterView.self)
        view.isHidden = true
        APPWindow?.addSubview(view)
        return view
    }()
    
    //MARK: --------------------生命周期--------------------
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
        bindAction()
        addConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setUI()
        setShareTextView()
        bindAction()
        addConstraints()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        ZMUtil.clipCircle(view: contentView, Corner: [.topLeft, .topRight], radius: 12)
    }

    //MARK: --------------------UI--------------------
    func setUI() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib.init(nibName: "TBSharePOPViewImageCell", bundle: nil), forCellWithReuseIdentifier: "TBSharePOPViewImageCell")
    }
    
    func addConstraints() {
        
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        goodsInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.imgArr = resp.imgs.components(separatedBy: ",").map({ url in
                    return ["url":url,"select":"0"]
                })
                self.imgArr[0]["select"] = "1"
                self.poster.goodsInfo.accept(resp)
                self.poster.img.accept(self.imgArr[0]["url"]!)
                self.setSaveBtn()
                self.collectionView.reloadData()
                self.setShareTextView()
            }
        }).disposed(by: disposeBag)
        
        jdGoodsInfo.subscribe(onNext:{ [unowned self] resp in
            if let data = resp {
                if let imgs = data.imageInfo?.imageList {
                    self.imgArr = imgs.map({ val in
                        return ["url":val.url,"select":"0"]
                    })
                }
                self.imgArr[0]["select"] = "1"
                self.poster.jdGoodsInfo.accept(data)
                self.poster.img.accept(self.imgArr[0]["url"]!)
                self.setSaveBtn()
                self.collectionView.reloadData()
                self.setShareTextView()
            }
        }).disposed(by: disposeBag)
        
        pddGoodsInfo.subscribe(onNext:{ [unowned self] resp in
            if let data = resp {
                self.imgArr = data.goodsGalleryUrls.map({ val in
                    return ["url":val,"select":"0"]
                })
                self.imgArr[0]["select"] = "1"
                self.poster.pddGoodsInfo.accept(data)
                self.poster.img.accept(self.imgArr[0]["url"]!)
                self.setSaveBtn()
                self.collectionView.reloadData()
                self.setShareTextView()
            }
        }).disposed(by: disposeBag)
        
        linkInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.poster.codeUrl.accept(resp.shortUrl)
                self.setShareTextView()
            }
        }).disposed(by: disposeBag)
        
        imgCount.rx.tap.subscribe(onNext:{ [unowned self] resp in
//            if self.selectImgcount == 0 {
//                return ZMToast.showToast(title: "请选择图片")
//            }
//            ZMToast.showActivity()
//            for i in 0 ..< self.imgArr.filter({return $0["select"] == "1"}).count {
//                let cell = self.collectionView.cellForItem(at: IndexPath(item: i, section: 0)) as! TBSharePOPViewImageCell
//                UIImageWriteToSavedPhotosAlbum(cell.img.image!, self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
//            }
            self.shareSaveBtn.sendActions(for: .touchUpInside)
        }).disposed(by: disposeBag)
        
        addressBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.addressBtn.isSelected = !self.addressBtn.isSelected
            self.setShareTextView()
        }).disposed(by: disposeBag)
        
        inviteBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.inviteBtn.isSelected = !self.inviteBtn.isSelected
            self.setShareTextView()
        }).disposed(by: disposeBag)
        
        copyLinkBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.linkInfo.value?.shortUrl
            ZMToast.showToast(title: "已复制")
        }).disposed(by: disposeBag)
        
        copyTxtBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.shareTxtView.text ?? ""
            ZMToast.showToast(title: "已复制")
        }).disposed(by: disposeBag)
        
        copyTxt.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.shareTxtView.text ?? ""
            ZMToast.showToast(title: "已复制")
        }).disposed(by: disposeBag)
        
        shareWXBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.shareTxtView.text ?? ""
            ZMToast.showToast(title: "分享文案已复制")
            let dic = NSMutableDictionary()
            let img = ZMOcHelper.image(withCaputureView: self.poster.contentView)
            dic.ssdkSetupShareParams(byText: "", images: [img], url: URL(string: ""), title: "", type: .auto)
            ZMShareManager.share(0, dic)
        }).disposed(by: disposeBag)
        
        shareFrindBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.shareTxtView.text ?? ""
            ZMToast.showToast(title: "分享文案已复制")
            let dic = NSMutableDictionary()
            let img = ZMOcHelper.image(withCaputureView: self.poster.contentView)
            dic.ssdkSetupShareParams(byText: "", images: [img], url: URL(string: ""), title: "", type: .auto)
            ZMShareManager.share(1, dic)
        }).disposed(by: disposeBag)
        
        shareCopyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if let link = self.linkInfo.value {
                UIPasteboard.general.string = link.shortUrl
                ZMToast.showToast(title: "链接已复制")
            }
        }).disposed(by: disposeBag)
        
        shareSaveBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.poster.saveView()
        }).disposed(by: disposeBag)
    }
    
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            ZMToast.showToast(title: "保存失败")
            return
        }
        saveSuccess += 1
        if selectImgcount == saveSuccess {
            ZMToast.showToast(title: "保存成功")
        }
    }
    
    func setSaveBtn() {
        selectImgcount = imgArr.filter({return $0["select"] == "1"}).count
        imgCount.setTitle("保存图片\(selectImgcount)/\(self.imgArr.count)", for: .normal)
    }
    
    func setShareTextView() {
        var txt = ""
        if let resp = goodsInfo.value {
            txt = "【\(resp.title)】\n【 原价 】\(resp.originalPrice.zm.toString(keep: 2))元"
            if resp.actualPrice > 0 {
                txt = txt + "\n【券后价】\(resp.actualPrice.zm.toString(keep: 2))元"
            }
        } else if let resp = jdGoodsInfo.value {
            txt = "【\(resp.skuName)】\n【 原价 】\(resp.lowestPrice.zm.toString(keep: 2))元"
            if resp.lowestCouponPrice > 0 {
                txt = txt + "\n【券后价】\(resp.lowestCouponPrice.zm.toString(keep: 2))元"
            }
        } else if let resp = pddGoodsInfo.value {
            txt = "【\(resp.goodsName)】\n【 原价 】\(resp.oldPrice.zm.toString(keep: 2))元"
            if resp.couponPrice > 0 {
                txt = txt + "\n【券后价】\(resp.currentPrice.zm.toString(keep: 2))元"
            }
        }
        txt = txt + "\n---------------------"
        if let link = linkInfo.value {
            txt = txt + "\n【下单地址】\(link.shortUrl)"
        }
        if addressBtn.isSelected {
            txt = txt + "\n【注册赚钱】\(CONFIG_INVITEURL)"
        }
        if inviteBtn.isSelected {
            if let user = ZMAppShareData.share.userInfo.value {
                txt = txt + "\n【邀请码】\(user.showId)"
            }
        }
        shareTxtView.text = txt
    }
    
    @IBAction func onClose(_ sender: Any) {
        removeFromSuperview()
    }
    
    //MARK: --------------------delegate--------------------
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TBSharePOPViewImageCell", for: indexPath) as! TBSharePOPViewImageCell
        cell.img.zm.setImage(urlStr: imgArr[indexPath.row]["url"]!)
        cell.selectImg.isSelected = imgArr[indexPath.row]["select"] == "1"
//        cell.selectImg.rx.tap.subscribe(onNext:{ [unowned self] resp in
//            cell.selectImg.isSelected = !cell.selectImg.isSelected
//            self.imgArr[indexPath.row]["select"] = "1"
//            self.setSaveBtn()
//        }).disposed(by: cell.disposeBag)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        for i in 0..<imgArr.count {
            imgArr[i]["select"] = (i == indexPath.row ? "1" : "0")
        }
        self.poster.img.accept(imgArr[indexPath.row]["url"]!)
//        imgArr[indexPath.row]["select"] = imgArr[indexPath.row]["select"] == "1" ? "0" : "1"
        setSaveBtn()
        collectionView.reloadData()
    }

}
